import axios from "axios";
import { dtEquipment } from "@/api/index";

const originAxios = axios.create();

function addAuthorization (config) {
  let headers = config.headers;
  let token = sessionStorage.getItem("dtUseToken");
  if (token) {
    headers["Authorization"] = "Bearer " + token;
  } else {
    return config.data
  }
}

// axios默认配置
originAxios.defaults.timeout = 10000; // 超时时间
originAxios.defaults.baseURL = process.env.NODE_ENV === "production" ? `https://gateway.wlyuan.com.cn` : `192.168.1.253:40201`

// http request 拦截器
originAxios.interceptors.request.use(
  (config) => {
    config.headers["Content-Type"] = "application/json;charset=UTF-8";
    config.headers["Access-Control-Allow-Origin"] = "*";
    config.headers["Access-Control-Allow-Header"] = "Content-Type,*";
    addAuthorization(config);
    sessionStorage.removeItem("dtUseToken");
    return config;
  },
  (error) => {
    return Promise.reject(error.response);
  }
);

async function getDtToken () {
  const url = `/api/v1.0/getToken`;
  return await originAxios.get(url);
}


const DT_EQUIPMENT_TYPES = {
  DT_TOKEN: 'DT_TOKEN',
  EXPORTS_COUNT: "EXPORTS_COUNT"
};

const state = {
  dtToken: null,
  exportsCount: 0
};
const getters = {};

const mutations = {
  [DT_EQUIPMENT_TYPES.DT_TOKEN] (state, dtToken) {
    state.dtToken = dtToken;
  },
  [DT_EQUIPMENT_TYPES.EXPORTS_COUNT] (state, exportsCount) {
    state.exportsCount = exportsCount;
  }
};

const actions = {
  async getDtUrlParams ({ commit, dispatch }, { params }) {
    let response = await getDtToken()
    const { data } = response
    sessionStorage.setItem("token", data?.data);
    commit(DT_EQUIPMENT_TYPES.DT_TOKEN, data?.data)

    let searchData = await dispatch('search', { data: params })
    if (searchData.data?.code === 0) {
      const { data } = searchData?.data
      return data
    }
  },
  updateExportsCount ({ commit }, { count }) {
    commit(DT_EQUIPMENT_TYPES.EXPORTS_COUNT, count)
  },
  async search ({ commit }, { data }) {
    let response = await dtEquipment.getDeviceData(data)
    return response
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
